export type PipelineContext = Record<string, any>

export type PipelineMiddleware<T extends PipelineContext = PipelineContext> = (ctx: T, next: (() => void) | (() => void)) => void

/**
 * 支持异步和同步的流水线
 */
export type Middleware<T> = (context: T, next: () => void) => void;

export class Pipeline<T> {
  private middlewares: Array<Middleware<T>> = [];

  use (middleware: Middleware<T>): void {
    this.middlewares.push(middleware);
  }

  run (context: T): T {
    const runMiddleware = (index: number): T => {
      if (index < this.middlewares.length) {
        this.middlewares[index](context, () => runMiddleware(index + 1));
      }
      return context
    };
    return runMiddleware(0);
  }
}
